from pyecharts.charts import Geo
from pyecharts import options as opts
from pyecharts.globals import ChartType
from pyecharts.charts import Map


mode = 3  # 控制绘制的热力图模式 0 表示按省份绘制， 1 表示按城市绘制 2 表示绘制2023.1省份热力图 3 表示绘制2023.1各省份景区票价热力图


def data_handle():
    data = []
    map_city_dict = {}
    reduce_dict = {}
    string = "河北、山西、黑龙江、吉林、辽宁、江苏、浙江、安徽、福建、江西、山东、河南、湖北、湖南、广东、海南、四川、贵州、云南、陕西、甘肃、青海、内蒙古、广西、西藏、宁夏、新疆、北京、天津、上海、重庆"
    province = string.split("、")
    # print(province)

    with open("./马蜂窝各城市游记浏览量排行.csv", 'r') as f:
        # line = f.read().replace("\"", "")
        line = f.read().split("\n")
        for i in range(1, len(line)):
            data.append(line[i])
    # print(data)

    # 初始化省份规约字典
    for i in province:
        reduce_dict[i] = 0
    # print(reduce_dict)

    # 得到{省份:浏览量}格式的字典
    for i in data:
        i = i.split(",")  # 每一行数据按,分割
        # print(i)
        # map_dict[i[2]] = int(i[1])
        i[2] = i[2].replace("市", "")  # 数据清洗
        reduce_dict[i[2]] += int(i[1])
    # print(reduce_dict)

    # 得到{城市,浏览量}格式的字典
    for i in data:
        i = i.split(",")
        if i[0] in ['普洱', '克孜勒苏柯尔克孜自治州']:
            continue
        map_city_dict[i[0]] = int(i[1])
    print(map_city_dict)

    return reduce_dict, map_city_dict


def draw(reduce_dict=None, data_list=None, max_n=None):
    data = []
    if reduce_dict is None:  # 绘制2023.1热力图
        for i in data_list:
            i = list(i)
            # print(i)
            i[0] = i[0].replace("特别行政区", "").replace("自治区", "").replace("壮族", "").replace("回族", "").replace("维吾尔", "")
            i[1] /= 1000
            data.append(i)
        max_ = max_n / 1000
    else:  # 绘制城市热力图
        province = list(reduce_dict.keys())
        hot_value = list(reduce_dict.values())
        print(max(hot_value), min(hot_value))
        max_ = max(hot_value)
        # print(province, hot_value)
        for i in range(len(hot_value)):
            # hot_value[i] /= 220000
            if province[i] in ['浙江']:
                if mode == 1:
                    hot_value[i] /= 150000
                    max_ /= 150000  # 不同mode，max_只缩放一次，因此放在这个位置最合适
                if mode == 0:
                    hot_value[i] /= 220000
                    max_ /= 220000
            else:
                if mode == 1:
                    hot_value[i] /= 80000
                if mode == 0:
                    hot_value[i] /= 220000
            data.append((province[i], hot_value[i]))

    print(data)
    print(max_)
    c = (
        Geo(init_opts=opts.InitOpts(width="1400px", height="1000px"))  # 图表大小，主题风格 """theme='wonderland'"""
        .add_schema(maptype="china",  # 地图
                    itemstyle_opts=opts.ItemStyleOpts(color="#fffdf9", border_color="#f0ccab"))  # 背景颜色以及边框颜色
        .add(
            "",  # 系列名称，可以不设置
            data,  # 数据，一个元组的队列
            type_=ChartType.EFFECT_SCATTER,  # 点样式：涟漪
            effect_opts=opts.EffectOpts(symbol_size=10)  # 标记大小
        )

        .set_series_opts(label_opts=opts.LabelOpts(is_show=False))  # 不显示标签
        .set_global_opts(title_opts=opts.TitleOpts(title="全国各省份热度",  # 图表标题
                                                   pos_left="center",  # 标题位置
                                                   subtitle="数据来源：“马蜂窝", ),  # 副标题
                         visualmap_opts=opts.VisualMapOpts(max_=100,
                                                           range_text=["火爆", '平淡'],  # 色彩图例上下的标题
                                                           split_number=5,
                                                           pos_left="25%",  # 图例页面位置
                                                           pos_top="47%",
                                                           # is_piecewise=True,
                                                           # pieces=[{"min": 1, "max": 20, "color": "#32efcf",
                                                           #          "label": "平淡"},
                                                           #         {"min": 21, "max": 40, "color": "#32e0c4",
                                                           #          "label": "平常"},
                                                           #         {"min": 41, "max": 60, "color": "#b8de6f",
                                                           #          "label": "人气"},
                                                           #         {"min": 61, "max": 80, "color": "#fd8c04",
                                                           #          "label": "热门"},
                                                           #         {"min": 81, "max": 141, "color": "ec5858",
                                                           #          "label": "火爆"}]
                                                                     )))
    c.render("../image/%s.html" % mode)


def data_handle2():
    list1 = []
    list2 = []
    sold_data = []
    price_data = []
    with open("../csv文件/去哪儿各省份2023.1旅游数据统计.csv", "r", encoding="utf-8") as f:
        lines = f.read().split('\n')
        for line in lines:
            line = line.split(",")
            if line[0] == "省份":
                continue
            # if float(line[2]) > 200:
            #     line[2] = 200
            tmp1 = (line[0], int(line[1]))
            tmp2 = (line[0], float(line[2]))
            list1.append(line[0])
            list2.append(int(line[1]))
            sold_data.append(tmp1)
            price_data.append(tmp2)
        print(sold_data)
        print(price_data)
        max_ = max(list2)
        min_ = min(list2)
        print(max_, min_)
    return sold_data, price_data, max_


def draw2(data_list):
    c = (
        Map(init_opts=opts.InitOpts(width="1000px", height="600px"))
        .add("", data_list, "china")
        .set_global_opts(
            title_opts=opts.TitleOpts(title="“去哪儿”2023.1全国各省景区平均票价",
                                      pos_bottom="90%",
                                      pos_right="20%"),
            visualmap_opts=opts.VisualMapOpts(type_="color",
                                              max_=200, range_text=['平均票价', ''],
                                              is_piecewise=True,
                                              pos_top="middle",
                                              pos_left="left",
                                              orient="vertical",
                                              pieces=[{"min": 0, "max": 50, "color": "#f9f59f", "label": "<50"},
                                                      {"min": 50, "max": 70, "color": "#f1e93b", "label": "50-70"},
                                                      {"min": 70, "max": 100, "color": "#f7b564", "label": "70-100"},
                                                      {"min": 100, "max": 150, "color": "#f78e64", "label": "100-150"},
                                                      {"min": 150, "max": 300, "color": "#b90922", "label": ">150"}],
                                              # tooltip_opts = opts.TooltipOpts(formatter="{c} %")
                                              )
            # .render("map_visualmap_piecewise.html")
        )
    )
    c.render("../image/2023.1全国各省景区平均门票价格.html")


if __name__ == '__main__':
    if mode == 0 or mode == 1:
        reduce_dict = data_handle()
        draw(reduce_dict[mode])
    elif mode == 2:
        x = data_handle2()
        draw(data_list=x[0], max_n=x[2])
    elif mode == 3:
        x = data_handle2()
        draw2(data_list=x[1])
